<template>
  <div class="page-container">
    <div class="form-header">
      <h1>添加课程</h1>
      <p>创建新的课程信息</p>
    </div>
    
    <el-card class="form-card">
      <el-form
        :model="courseForm"
        :rules="courseRules"
        ref="courseFormRef"
        label-width="100px"
        size="large"
      >
        <el-form-item label="课程名称" prop="title">
          <el-input 
            v-model="courseForm.title" 
            placeholder="请输入课程名称"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="课程简介" prop="body">
          <el-input
            v-model="courseForm.body"
            type="textarea"
            :rows="4"
            placeholder="请输入课程简介"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="课程图片" prop="picPaths">
          <el-input 
            v-model="courseForm.picPaths" 
            placeholder="请输入课程图片URL"
          />
        </el-form-item>
        
        <el-form-item label="所属分类" prop="categoryid">
          <el-select 
            v-model="courseForm.categoryid" 
            placeholder="请选择课程分类"
            style="width: 100%"
            :loading="loadingCategories"
          >
            <el-option
              v-for="category in categories"
              :key="category.id"
              :label="category.title"
              :value="category.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="上课时间" prop="startTime">
          <el-date-picker
            v-model="courseForm.startTime"
            type="datetime"
            placeholder="选择上课时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="x"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            v-model="courseForm.endTime"
            type="datetime"
            placeholder="选择结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="x"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item>
          <div class="form-actions">
            <el-button size="large" @click="resetForm">重置</el-button>
            <el-button 
              type="primary" 
              size="large" 
              @click="handleSubmit"
              :loading="submitting"
            >
              创建课程
            </el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../stores/user'
import { ElMessage } from 'element-plus'
import * as api from '../services/api'

const router = useRouter()
const userStore = useUserStore()
const courseFormRef = ref()
const submitting = ref(false)
const loadingCategories = ref(false)
const categories = ref([])

const courseForm = reactive({
  title: '',
  body: '',
  picPaths: '',
  categoryid: '',
  startTime: '',
  endTime: ''
})

const courseRules = {
  title: [
    { required: true, message: '请输入课程名称', trigger: 'blur' }
  ],
  body: [
    { required: true, message: '请输入课程简介', trigger: 'blur' }
  ],
  categoryid: [
    { required: true, message: '请选择课程分类', trigger: 'change' }
  ],
  startTime: [
    { required: true, message: '请选择上课时间', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择结束时间', trigger: 'change' },
    {
      validator: (rule, value, callback) => {
        if (value && courseForm.startTime && parseInt(value) <= parseInt(courseForm.startTime)) {
          callback(new Error('结束时间必须晚于开始时间'))
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ]
}

const loadCategories = async () => {
  try {
    loadingCategories.value = true
    const response = await api.getAllCategories()
    categories.value = Array.isArray(response) ? response : []
  } catch (error) {
    console.error('获取分类列表失败:', error)
    ElMessage.error('获取分类列表失败')
    categories.value = []
  } finally {
    loadingCategories.value = false
  }
}

const handleSubmit = async () => {
  if (!courseFormRef.value) return
  
  try {
    await courseFormRef.value.validate()
    submitting.value = true
    
    // 准备提交数据
    const submitData = {
      title: courseForm.title,
      body: courseForm.body,
      picPaths: courseForm.picPaths,
      categoryid: courseForm.categoryid,
      startTime: parseInt(courseForm.startTime), // 转换为Unix时间戳
      endTime: parseInt(courseForm.endTime), // 转换为Unix时间戳
      userid: userStore.user.id
    }
    
    await api.addCourse(submitData)
    
    ElMessage.success('课程创建成功！')
    router.push('/home')
    
  } catch (error) {
    console.error('创建课程失败:', error)
    ElMessage.error('创建课程失败')
  } finally {
    submitting.value = false
  }
}

const resetForm = () => {
  if (courseFormRef.value) {
    courseFormRef.value.resetFields()
  }
}

onMounted(() => {
  loadCategories()
})
</script>

<style scoped>
.page-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.form-header {
  text-align: center;
  margin-bottom: 30px;
}

.form-header h1 {
  font-size: 28px;
  color: #303133;
  margin: 0 0 10px 0;
}

.form-header p {
  color: #606266;
  font-size: 16px;
  margin: 0;
}

.form-card {
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  width: 100%;
}
</style>